using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XProject.DAO;
using XProject.Entity;
using System.Configuration;
namespace XProject.GUI
{
    public partial class DiaryTool : Form
    {      
        DiaryDAO daoDiary = new DiaryDAO();
        IconDAO daoIcon = new IconDAO();
        DiaryItem diary = new DiaryItem();
        DateTime curDateTime = DateTime.Now;
        Image imgEmpty;
        int mode=0;
        bool textchanged = false;
        public DiaryTool()
        {
            InitializeComponent();
            imgEmpty = Image.FromFile(Application.StartupPath+"\\emotions\\"+ daoIcon.GetIconByName("none").ImagePath);
        }

        private void DiaryTool_Load(object sender, EventArgs e)
        {
            //set icon
            //string icon =Application.StartupPath+"\\"+ ConfigurationManager.AppSettings["icon"];
            //if (System.IO.File.Exists(icon)) { this.Icon = new Icon(icon); }
            //load data
            cmbSize.Items.AddRange(new object[] { 8, 10, 12, 14, 16, 18, 24, 36, 48, 72 });
            dtpDate.Value = curDateTime; btnGo_Click(sender,e);
            lblBeginningDate.Text = daoDiary.GetFirstDate().ToShortDateString();
            
        }

        private void btnBold_Click(object sender, EventArgs e)
        {
            System.Drawing.Font curFont = rtfDiary.SelectionFont;
            System.Drawing.FontStyle fontStyle = new FontStyle();
            fontStyle = curFont.Style;
            if ((fontStyle&FontStyle.Bold)==FontStyle.Bold)
            {
                fontStyle &= ~FontStyle.Bold;
               // MessageBox.Show(((int)fontStyle).ToString());
            }
            else
            {
                fontStyle |= FontStyle.Bold;
            }
            rtfDiary.SelectionFont = new Font(curFont, fontStyle);

        }

        private void btnColor_Click(object sender, EventArgs e)
        {
            ColorDialog dlgColor = new ColorDialog();
            if(dlgColor.ShowDialog()==DialogResult.OK)
            rtfDiary.SelectionColor = dlgColor.Color;
        }

        private void btnFont_Click(object sender, EventArgs e)
        {
            FontDialog dlgFont = new FontDialog();
            if (dlgFont.ShowDialog() == DialogResult.OK)
                rtfDiary.SelectionFont = dlgFont.Font;
            
        }



        private void btnUnderline_Click(object sender, EventArgs e)
        {
            System.Drawing.Font curFont = rtfDiary.SelectionFont;           
            System.Drawing.FontStyle fontStyle = new FontStyle();
            fontStyle = curFont.Style;
            if ((fontStyle&FontStyle.Underline)==FontStyle.Underline)
            {
                fontStyle &= ~FontStyle.Underline;
            }
            else
            {
                fontStyle |= FontStyle.Underline;
            }
            rtfDiary.SelectionFont = new Font(curFont, fontStyle);
        }

        private void btnItalic_Click(object sender, EventArgs e)
        {
            System.Drawing.Font curFont = rtfDiary.SelectionFont;
            System.Drawing.FontStyle fontStyle = new FontStyle();
            fontStyle = rtfDiary.SelectionFont.Style;
            if ((fontStyle&FontStyle.Italic)==FontStyle.Italic)
            {
                fontStyle &= ~FontStyle.Italic;
            }
            else
            {
                fontStyle |= FontStyle.Italic;               
            }
            rtfDiary.SelectionFont = new Font(curFont, fontStyle);
        }

        private void btnUndo_Click(object sender, EventArgs e)
        {
            if (rtfDiary.CanUndo) rtfDiary.Undo();
            else { btnUndo.Enabled = false; btnRedo.Enabled = true; }
        }

        private void btnRedo_Click(object sender, EventArgs e)
        {
            if (rtfDiary.CanRedo) rtfDiary.Redo();
            else { btnRedo.Enabled = false; btnUndo.Enabled = true; }
        }

        private void btnCut_Click(object sender, EventArgs e)
        {
            if (rtfDiary.SelectedRtf != "") rtfDiary.Cut();
        }

        private void btnPaste_Click(object sender, EventArgs e)
        {
            if(rtfDiary.CanPaste(DataFormats.GetFormat(DataFormats.Text)))rtfDiary.Paste();
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            if (rtfDiary.SelectedRtf != "") rtfDiary.Copy();
        }

        private void btnAlignLeft_Click(object sender, EventArgs e)
        {
            rtfDiary.SelectionAlignment = HorizontalAlignment.Left;
        }

        private void btnAlignCenter_Click(object sender, EventArgs e)
        {
            rtfDiary.SelectionAlignment = HorizontalAlignment.Center;
        }

        private void btnAlignRight_Click(object sender, EventArgs e)
        {
            rtfDiary.SelectionAlignment = HorizontalAlignment.Right;
        }
        /// <summary>
        /// Add or update the diary. 
        /// This method will automatically add a diary if there is 
        /// no diary in database corresponding to the selected date
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (diary.ItemID <= 0) mode = 1;
            else mode = 2;
            if (!IsValidInput())
                {
                    MessageBox.Show("The content cannot be empty.");
                    return;
                }
            diary.Date = dtpDate.Value;
            diary.Title = txtTitle.Text;
            diary.Status = txtStatus.Text;
            diary.Encrypted = btnEncrypted.Checked;
            diary.Content = rtfDiary.Rtf;
            if (diary.Icon.IconID == -1) diary.Icon.IconID = daoIcon.GetIconByName("none").IconID;
            diary.Account.AccountID = MainForm.CurrentAccount.AccountID;//set current user id here

            if (mode == 1)
            {
                
                if (daoDiary.Insert(diary) > 0)
                {
                    MessageBox.Show("Success");
                    textchanged = false;
                }
                else MessageBox.Show(daoDiary.Message);
            }
            else if (mode == 2)
            {
                if (daoDiary.Update(diary) > 0)
                {
                    MessageBox.Show("Updated successfully");
                    textchanged = false;
                }
                else MessageBox.Show(daoDiary.Message);
            }
        }

        private void rtfDiary_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.B) btnBold_Click(sender, e);
        }
        /// <summary>
        /// Turn on/off bullet
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBullet_Click(object sender, EventArgs e)
        {
            if (!rtfDiary.SelectionBullet) rtfDiary.SelectionIndent += 15;
            else rtfDiary.SelectionIndent -= 15;
            rtfDiary.SelectionBullet = !rtfDiary.SelectionBullet;
            
        }

        private void btnIndentUp_Click(object sender, EventArgs e)
        {
            rtfDiary.SelectionIndent += 15;
        }

        private void btnIndentDown_Click(object sender, EventArgs e)
        {
            rtfDiary.SelectionIndent -= 15;
        }

        private void rtfDiary_SelectionChanged(object sender, EventArgs e)
        {
            if (rtfDiary.SelectionFont != null)
            {
                cmbSize.Text = rtfDiary.SelectionFont.Size.ToString();
                lblFont.Text = rtfDiary.SelectionFont.Name;
            }
        }

        private void rtfDiary_TextChanged(object sender, EventArgs e)
        {
            lblCountRemain.Text = Convert.ToString(64000 - rtfDiary.Rtf.Length);
            if (!textchanged) textchanged=true;
        }

        private void dtpDate_ValueChanged(object sender, EventArgs e)
        {
            if (!textchanged)
            {
                curDateTime = dtpDate.Value;
            }
                        
        }

        private void cmbSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            int size = 0;
            try
            {
                size = int.Parse(cmbSize.SelectedItem.ToString());
                if (size > 0)
                {
                    Font f = rtfDiary.SelectionFont;
                    rtfDiary.SelectionFont = new Font(f.FontFamily, size, f.Style);
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message,"Error");
            }

        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (textchanged)
                if (MessageBox.Show("The content has been changed. Are you sure want to leave without saving?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                    return;
                    dtpDate.Value = dtpDate.Value.AddDays(-1);
                    btnGo_Click(sender,e);                
            
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (textchanged)
                if (MessageBox.Show("The content has been changed. Are you sure want to leave without saving?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                    return;
                    dtpDate.Value = dtpDate.Value.AddDays(1);
                    btnGo_Click(sender,e);
                 
                
            
        }
       
     //check if input is valid
        bool IsValidInput()
        {
            if (rtfDiary.Text.Trim() == "") return false;
            return true;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("Are you sure want to delete this?","Confirm",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2)==DialogResult.Yes)
            if (daoDiary.Delete(diary) > 0)
            {
                MessageBox.Show("Deleted successfully");
                rtfDiary.Text = "[Deleted]";
            }
            else MessageBox.Show(daoDiary.Message,"Error");
        }

        private void btnTime_Click(object sender, EventArgs e)
        {
            Clipboard.SetText("\n["+DateTime.Now.ToLongTimeString()+"]\n");
            rtfDiary.Paste();
        }

        private void btnEncrypted_Click(object sender, EventArgs e)
        {
            btnEncrypted.Checked = !btnEncrypted.Checked;
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {

            if (textchanged)
                if (MessageBox.Show("The content has been changed. Are you sure want to leave without saving?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                    return;
                    DateTime minDate = daoDiary.GetFirstDate();
                    if (minDate != DateTime.MinValue)
                    {
                        dtpDate.Value = minDate;
                        btnGo_Click(sender,e);
                    }
                
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (textchanged)
                if (MessageBox.Show("The content has been changed. Are you sure want to leave without saving?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                    return;
                    DateTime maxDate = daoDiary.GetLastDate();
                    if (maxDate != DateTime.MinValue)
                    {
                        dtpDate.Value = maxDate;
                        btnGo_Click(sender, e);
                    }
                
            
        }

        private void rtfDiary_StyleChanged(object sender, EventArgs e)
        {
            if (!textchanged) textchanged = true;
        }

        private void DiaryTool_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(textchanged)
                if (MessageBox.Show("The content has been changed. Are you sure want to close without saving?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                {
                    e.Cancel = true;
                }
        }

        private void txtTitle_TextChanged(object sender, EventArgs e)
        {
            if (!textchanged) textchanged = true;
        }

        private void txtStatus_TextChanged(object sender, EventArgs e)
        {
            if (!textchanged) textchanged = true;
        }

        private void picEmotion_Click(object sender, EventArgs e)
        {
            ImageChooser imgChooser = new ImageChooser();
            if (imgChooser.ShowDialog() == DialogResult.OK)
            {
                diary.Icon.IconID = imgChooser.FeelingIcon.IconID;
                diary.Icon.ImagePath = imgChooser.FeelingIcon.ImagePath;
                picEmotion.BorderStyle = BorderStyle.None;             
                picEmotion.Image = Image.FromFile(Application.StartupPath+"\\emotions\\"+ imgChooser.FeelingIcon.ImagePath);
            
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (textchanged)
            {
                if (MessageBox.Show("Are you sure want to leave without saving?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                {
                    dtpDate.Value = curDateTime;
                    return; 

                }
            }
            diary = daoDiary.GetDiaryByDate(dtpDate.Value, MainForm.CurrentAccount.AccountID);//set account id
            if (diary != null)
            {
                if (diary.Encrypted)
                {
                    diary.EncryptedTitle = diary.Title;
                    diary.EncryptedStatus = diary.Status;
                    diary.EncryptedContent = diary.Content;
                }
                txtTitle.Text = diary.Title;
                txtStatus.Text = diary.Status;
                rtfDiary.Rtf = diary.Content;
                btnEncrypted.Checked = diary.Encrypted;
                curDateTime = dtpDate.Value;
                if (diary.Icon.ImagePath != "")
                    picEmotion.Image = Image.FromFile(Application.StartupPath+"\\emotions\\"+diary.Icon.ImagePath);
                else picEmotion.Image = imgEmpty;
                textchanged = false;

            }
            else
            {
                if (daoDiary.Message != "") MessageBox.Show(daoDiary.Message);
            }
        }

    }
}